package carpediem.xin.tamplate.network;

import carpediem.xin.tamplate.constants.IErrorCode;
import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;
import timber.log.Timber;

/**
 * Created by zhaijianwei on 16/12/8.
 */

public abstract class HttpResultSubscriber<T> extends Subscriber<HttpResult<T>> {
    private static final String TAG = HttpResultSubscriber.class.getSimpleName();

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        Timber.tag(TAG).e(e.toString());
        /*全局的异常处理*/
        if (e instanceof HttpException) {
            //// TODO: 16/12/8 do something
        }
        _onError(e);
    }

    @Override
    public void onNext(HttpResult<T> result) {
        if (null == result) {
            _onError(new NullPointerException("result object is null"));
        } else if (IErrorCode.SUCCESS != result.errorCode) {
            switch (result.errorCode) {
            }
            Timber.tag(TAG).v("errorCode = " + result.errorCode + "; errorMsg = " + result.errorMsg);
            _onError(new Throwable(result.errorMsg));
        } else {
            onSuccess(result.data);
        }
    }

    /**
     * 接口调用成功的业务回调，已处理null等情况，用于override
     */
    public abstract void onSuccess(T t);

    /**
     * 接口调用错误的业务回调，可添加通用异常处理，用于override
     */
    public abstract void _onError(Throwable e);
}
